# -*- coding: utf-8 -*-
"""
相机设备选择对话框
"""

from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                             QListWidget, QPushButton, QListWidgetItem, QMessageBox)
from PyQt5.QtCore import Qt
import cv2

class CameraSelectionDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("选择相机设备")
        self.setModal(True)
        self.setFixedSize(400, 300)
        
        self.selected_camera_index = -1
        self.camera_list = []
        
        self.init_ui()
        self.scan_cameras()
    
    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout()
        
        # 标题标签
        title_label = QLabel("检测到以下相机设备，请选择要使用的设备：")
        title_label.setStyleSheet("font-weight: bold; font-size: 12px; margin: 10px;")
        layout.addWidget(title_label)
        
        # 相机列表
        self.camera_list_widget = QListWidget()
        self.camera_list_widget.setSelectionMode(QListWidget.SingleSelection)
        layout.addWidget(self.camera_list_widget)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新设备列表")
        refresh_btn.clicked.connect(self.scan_cameras)
        button_layout.addWidget(refresh_btn)
        
        button_layout.addStretch()
        
        # 确定和取消按钮
        ok_btn = QPushButton("确定")
        ok_btn.clicked.connect(self.accept)
        ok_btn.setDefault(True)
        
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        
        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def scan_cameras(self):
        """扫描可用的相机设备"""
        self.camera_list_widget.clear()
        self.camera_list = []
        
        # 扫描前10个相机索引
        max_cameras = 10
        available_cameras = []
        
        for i in range(max_cameras):
            try:
                cap = cv2.VideoCapture(i, cv2.CAP_DSHOW)  # 使用DirectShow后端
                if cap.isOpened():
                    # 尝试读取一帧来确认相机可用
                    ret, frame = cap.read()
                    if ret:
                        # 获取相机信息
                        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        fps = cap.get(cv2.CAP_PROP_FPS)
                        
                        camera_info = {
                            'index': i,
                            'name': f"相机 {i}",
                            'resolution': f"{width}x{height}",
                            'fps': fps
                        }
                        available_cameras.append(camera_info)
                    
                    cap.release()
            except Exception as e:
                continue
        
        # 如果没有找到相机，添加默认选项
        if not available_cameras:
            # 添加内置相机选项
            builtin_camera = {
                'index': -1,
                'name': "内置相机",
                'resolution': "未知",
                'fps': 0
            }
            available_cameras.append(builtin_camera)
        
        # 添加到列表控件
        for camera in available_cameras:
            item_text = f"{camera['name']} (分辨率: {camera['resolution']}"
            if camera['fps'] > 0:
                item_text += f", FPS: {camera['fps']:.1f}"
            item_text += ")"
            
            item = QListWidgetItem(item_text)
            item.setData(Qt.UserRole, camera)
            self.camera_list_widget.addItem(item)
        
        # 默认选择第一个
        if self.camera_list_widget.count() > 0:
            self.camera_list_widget.setCurrentRow(0)
    
    def get_selected_camera(self):
        """获取选中的相机信息"""
        current_item = self.camera_list_widget.currentItem()
        if current_item:
            return current_item.data(Qt.UserRole)
        return None
    
    def accept(self):
        """确认选择"""
        selected_camera = self.get_selected_camera()
        if selected_camera:
            self.selected_camera_index = selected_camera['index']
            super().accept()
        else:
            QMessageBox.warning(self, "警告", "请选择一个相机设备")
    
    @staticmethod
    def select_camera(parent=None):
        """静态方法：显示相机选择对话框并返回选中的相机索引"""
        dialog = CameraSelectionDialog(parent)
        if dialog.exec_() == QDialog.Accepted:
            return dialog.selected_camera_index
        return -1 